package com.cre_drt;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.GeolocInvalidException;
import com.att.intern.webservice.Webservice.TokenInvalidException;

@SuppressLint("SimpleDateFormat")
public class AddDamageAssessmentScreen extends ActivityTimeout {

	EditText glcEdit;
	EditText stateEdit;
	EditText pmEdit;
	EditText buildingNameEdit;
	EditText addressEdit;
	Spinner eventYearDropdown;
	EditText requestorUserIDEdit;
	EditText contactNumberEdit;
	EditText initialDateReportEdit;
	Spinner eventTypeDropdown;
	Spinner eventNameDropdown;
	Spinner propertyTypeDropdown;
	EditText workRequestNumber;
	Spinner buildingStatusDropdown;
	Spinner creLeadDropdown;
	EditText capitalEdit;
	EditText expenseEdit;
	EditText assessmentEdit;
	EditText statusEdit;
	Spinner reportOpenClosedSpinner;
	EditText completionDateEdit;
	EditText notesEdit;

	String commercialPower;
	String onGenerator;
	String damaged;
	String mobilityCo;
	String unoccupiable;

	HashMap<String, Integer> eventIds = new HashMap<String, Integer>() {
		private static final long serialVersionUID = 1L;
		{
			put("default", R.array.blankDropdown);
			put("hurricaneDropdown2010", R.array.hurricaneDropdown2010);
			put("hurricaneDropdown2011", R.array.hurricaneDropdown2011);
			put("hurricaneDropdown2012", R.array.hurricaneDropdown2012);
			put("hurricaneDropdown2013", R.array.hurricaneDropdown2013);
			put("earthquakeDropdown2010", R.array.earthquakeDropdown2010);
			put("earthquakeDropdown2011", R.array.earthquakeDropdown2011);
			put("earthquakeDropdown2012", R.array.earthquakeDropdown2012);
			put("earthquakeDropdown2013", R.array.earthquakeDropdown2013);
			put("floodDropdown2010", R.array.floodDropdown2010);
			put("floodDropdown2011", R.array.floodDropdown2011);
			put("floodDropdown2012", R.array.floodDropdown2012);
			put("floodDropdown2013", R.array.floodDropdown2013);
			put("ice stormDropdown2010", R.array.iceStormDropdown2010);
			put("ice stormDropdown2011", R.array.iceStormDropdown2011);
			put("ice stormDropdown2012", R.array.iceStormDropdown2012);
			put("ice stormDropdown2013", R.array.iceStormDropdown2013);
			put("snow stormDropdown2010", R.array.snowStormDropdown2010);
			put("snow stormDropdown2011", R.array.snowStormDropdown2011);
			put("snow stormDropdown2012", R.array.snowStormDropdown2012);
			put("snow stormDropdown2013", R.array.snowStormDropdown2013);
			put("tornadoDropdown2010", R.array.tornadoDropdown2010);
			put("tornadoDropdown2012", R.array.tornadoDropdown2011);
			put("tornadoDropdown2012", R.array.tornadoDropdown2012);
			put("tornadoDropdown2013", R.array.tornadoDropdown2013);
			put("wildfireDropdown2010", R.array.wildfireDropdown2010);
			put("wildfireDropdown2011", R.array.wildfireDropdown2011);
			put("wildfireDropdown2012", R.array.wildfireDropdown2012);
			put("wildfireDropdown2013", R.array.wildfireDropdown2013);
		}
	};

	String reqFields;
	boolean reqCheck;
	String geoloc;
	String geolocResult;
	String[] parsedResult;

	HashMap<String, String> sessionInfo;
	Webservice AddAssessmentWebservice;
	Incident newIncident;

	SessionManager session;
	SimpleDateFormat formatter;
	ProgressDialog progressDialog;
	InputMethodManager imm;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_damage_assessment_screen);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("Add Damage Assesment");
		actionBar.setSubtitle("Enter Information");

		session = new SessionManager(getApplicationContext());
		sessionInfo = session.getSessionDetails();
		newIncident = new Incident();
		formatter = new SimpleDateFormat("MM/dd/yyyy");

		reqFields = "The following fields are required:\n";
		reqCheck = true;
		geoloc = getIntent().getExtras().getString("geoloc");
		geolocResult = getIntent().getExtras().getString("geolocResult");

		parsedResult = geolocResult.split("~");

		setUpForm();

		AddAssessmentWebservice = new Webservice(getApplicationContext());

		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("Adding incident...");
		progressDialog.setCancelable(false);

		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.incident_search_screen, menu);
		return true;
	}

	@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
	private void setUpForm() {
		glcEdit = (EditText) findViewById(R.id.glcEdit);
		glcEdit.setKeyListener(null);
		glcEdit.setText(geoloc);
		newIncident.setGeoLoc(Integer.valueOf(geoloc));

		stateEdit = (EditText) findViewById(R.id.stateEdit);
		stateEdit.setKeyListener(null);
		stateEdit.setText(parsedResult[0]);
		newIncident.setState(parsedResult[0]);

		pmEdit = (EditText) findViewById(R.id.pmEdit);
		pmEdit.setKeyListener(null);
		pmEdit.setText(parsedResult[1]);
		newIncident.setPMAttuid(parsedResult[1]);

		buildingNameEdit = (EditText) findViewById(R.id.buildingNameEdit);
		buildingNameEdit.setKeyListener(null);
		buildingNameEdit.setText(parsedResult[2]);
		newIncident.setBuildingName(parsedResult[2]);

		addressEdit = (EditText) findViewById(R.id.addressEdit);
		addressEdit.setKeyListener(null);
		addressEdit.setText(parsedResult[3]);
		newIncident.setBuildingAddress(parsedResult[3]);

		// Event Name is driven by Event Year
		eventYearDropdown = (Spinner) findViewById(R.id.eventYearDropdown);
		eventYearDropdown.setSelection(3);
		eventNameDropdown = (Spinner) findViewById(R.id.eventNameDropdown);
		eventTypeDropdown = (Spinner) findViewById(R.id.eventTypeDropdown);
		String[] eventType = getResources().getStringArray(R.array.eventDropdown);
		ArrayAdapter<String> eventTypeAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventType);
		eventTypeDropdown.setAdapter(eventTypeAdapter);

		eventTypeDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
				String eventNameKey = eventTypeDropdown.getSelectedItem().toString().toLowerCase();
				if (eventNameKey.equalsIgnoreCase("Select Event Type")) {
					eventNameKey = "default";
				} else
					eventNameKey = eventNameKey + "Dropdown" + eventYearDropdown.getSelectedItem().toString();

				int eventNameId = eventIds.get(eventNameKey);
				String[] eventNames = getResources().getStringArray(eventNameId);
				ArrayAdapter<String> eventNameAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventNames);
				eventNameDropdown.setAdapter(eventNameAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		eventYearDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressLint("DefaultLocale")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
				String eventNameKey = eventTypeDropdown.getSelectedItem().toString().toLowerCase();
				if (eventNameKey.equalsIgnoreCase("Select Event Type")) {
					eventNameKey = "default";
				} else
					eventNameKey = eventNameKey + "Dropdown" + eventYearDropdown.getSelectedItem().toString();

				int eventNameId = eventIds.get(eventNameKey);
				String[] eventNames = getResources().getStringArray(eventNameId);
				ArrayAdapter<String> eventNameAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventNames);
				eventNameDropdown.setAdapter(eventNameAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		requestorUserIDEdit = (EditText) findViewById(R.id.requestorUserIDEdit);
		requestorUserIDEdit.setText(sessionInfo.get(session.KEY_USERNAME));
		newIncident.setReqATTUID(sessionInfo.get(session.KEY_USERNAME));

		contactNumberEdit = (EditText) findViewById(R.id.contactNumberEdit);
		contactNumberEdit.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

		initialDateReportEdit = (EditText) findViewById(R.id.initialReportDateEdit);
		String formattedDate = formatter.format(new Date());
		initialDateReportEdit.setText(formattedDate.toString());

		propertyTypeDropdown = (Spinner) findViewById(R.id.propertyTypeDropdown);
		propertyTypeDropdown.setSelection(0);
		propertyTypeDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
				String propertyType = propertyTypeDropdown.getSelectedItem().toString();
				CheckBox commercialPowerCheckBox = (CheckBox) findViewById(R.id.commercialPowerCheckBox);
				CheckBox onGeneratorCheckBox = (CheckBox) findViewById(R.id.onGeneratorCheckBox);
				if (propertyType.equals("CO")) {
					commercialPowerCheckBox.setChecked(false);
					onGeneratorCheckBox.setChecked(false);
					commercialPowerCheckBox.setTextColor(getResources().getColor(android.R.color.darker_gray));
					onGeneratorCheckBox.setTextColor(getResources().getColor(android.R.color.darker_gray));

					commercialPowerCheckBox.setFocusable(false);
					commercialPowerCheckBox.setClickable(false);
					onGeneratorCheckBox.setFocusable(false);
					onGeneratorCheckBox.setClickable(false);
				} else {
					commercialPowerCheckBox.setTextColor(getResources().getColor(android.R.color.black));
					onGeneratorCheckBox.setTextColor(getResources().getColor(android.R.color.black));
					commercialPowerCheckBox.setChecked(true);
					commercialPowerCheckBox.setFocusable(true);
					commercialPowerCheckBox.setClickable(true);
					onGeneratorCheckBox.setFocusable(true);
					onGeneratorCheckBox.setClickable(true);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		workRequestNumber = (EditText) findViewById(R.id.workRequestNumberEdit);

		capitalEdit = (EditText) findViewById(R.id.capitalEdit);
		expenseEdit = (EditText) findViewById(R.id.expenseEdit);
		assessmentEdit = (EditText) findViewById(R.id.assessmentEdit);
		statusEdit = (EditText) findViewById(R.id.statusEdit);

		completionDateEdit = (EditText) findViewById(R.id.completionDateEdit);
		formattedDate = formatter.format(new Date());
		Date defaultCompletionDate = new Date(new Date().getTime() + 1000 * 60 * 60 * 24);
		completionDateEdit.setText(formatter.format(defaultCompletionDate));

		notesEdit = (EditText) findViewById(R.id.notesEdit);

		newIncident.setComPowerIndicator("Y");
		newIncident.setOnGeneratorIndicator("N");
		newIncident.setDamageIndicator("N");
		newIncident.setMobCOIndicator("N");
		newIncident.setUnOccupiableIndicator("N");
		newIncident.setElecIssueIndicator("N");
		newIncident.setElecIssueClsdIndicator("N");
		newIncident.setEnvIssueIndicator("N");
		newIncident.setEnvIssueClsdIndicator("N");
		newIncident.setFenceGateIssueIndicator("N");
		newIncident.setFenceGateIssueClsdIndicator("N");
		newIncident.setGenIssueIndicator("N");
		newIncident.setGenIssueClsdIndicator("N");
		newIncident.setWaterIssueIndicator("N");
		newIncident.setWaterIssueClsdIndicator("N");
		newIncident.setGroundsIssueIndicator("N");
		newIncident.setGroundsIssueClsdIndicator("N");
		newIncident.setMechIssueIndicator("N");
		newIncident.setMechIssueClsdIndicator("N");
		newIncident.setOtherIssueIndicator("N");
		newIncident.setOtherIssueClsdIndicator("N");
		newIncident.setPlumbIssueIndicator("N");
		newIncident.setPlumbIssueClsdIndicator("N");
		newIncident.setRoofsIssueIndicator("N");
		newIncident.setRoofsIssueClsdIndicator("N");
		newIncident.setSafetyIssueIndicator("N");
		newIncident.setSafetyIssueClsdIndicator("N");
		newIncident.setStructIssueIndicator("N");
		newIncident.setStructIssueClsdIndicator("N");
	}

	public void onCheckboxClicked(View view) {
		boolean checked = ((CheckBox) view).isChecked();

		switch (view.getId()) {
		// Non-CO Facilities ONLY:
		case R.id.commercialPowerCheckBox:
			if (checked)
				newIncident.setComPowerIndicator("Y");
			else
				newIncident.setComPowerIndicator("N");
			break;
		case R.id.onGeneratorCheckBox:
			if (checked)
				newIncident.setOnGeneratorIndicator("Y");
			else
				newIncident.setOnGeneratorIndicator("N");
			break;

		// Any Facility
		case R.id.damagedCheckBox:
			if (checked)
				newIncident.setDamageIndicator("Y");
			else
				newIncident.setDamageIndicator("N");
			break;
		case R.id.mobilityCoCheckBox:
			if (checked)
				newIncident.setMobCOIndicator("Y");
			else
				newIncident.setMobCOIndicator("N");
			break;
		case R.id.unoccupiableCheckBox:
			if (checked)
				newIncident.setUnOccupiableIndicator("Y");
			else
				newIncident.setUnOccupiableIndicator("N");
			break;

		// Categories
		case R.id.electricalIssueCheckBox:
			if (checked)
				newIncident.setElecIssueIndicator("Y");
			else
				newIncident.setElecIssueIndicator("N");
			break;
		case R.id.electricalClosedCheckBox:
			if (checked)
				newIncident.setElecIssueClsdIndicator("Y");
			else
				newIncident.setElecIssueClsdIndicator("N");
			break;
		case R.id.environmentalIssueCheckBox:
			if (checked)
				newIncident.setEnvIssueIndicator("Y");
			else
				newIncident.setEnvIssueIndicator("N");
			break;
		case R.id.environmentalClosedCheckBox:
			if (checked)
				newIncident.setEnvIssueClsdIndicator("Y");
			else
				newIncident.setEnvIssueClsdIndicator("N");
			break;
		case R.id.fenceGatesIssueCheckBox:
			if (checked)
				newIncident.setFenceGateIssueIndicator("Y");
			else
				newIncident.setFenceGateIssueIndicator("N");
			break;
		case R.id.fenceGatesClosedCheckBox:
			if (checked)
				newIncident.setFenceGateIssueClsdIndicator("Y");
			else
				newIncident.setFenceGateIssueClsdIndicator("N");
			break;
		case R.id.generatorIssueCheckBox:
			if (checked)
				newIncident.setGenIssueIndicator("Y");
			else
				newIncident.setGenIssueIndicator("N");
			break;
		case R.id.generatorClosedCheckBox:
			if (checked)
				newIncident.setGenIssueClsdIndicator("Y");
			else
				newIncident.setGenIssueClsdIndicator("N");
			break;
		case R.id.waterIssueCheckBox:
			if (checked)
				newIncident.setWaterIssueIndicator("Y");
			else
				newIncident.setWaterIssueIndicator("N");
			break;
		case R.id.waterClosedCheckBox:
			if (checked)
				newIncident.setWaterIssueClsdIndicator("Y");
			else
				newIncident.setWaterIssueClsdIndicator("N");
			break;
		case R.id.groundsIssueCheckBox:
			if (checked)
				newIncident.setGroundsIssueIndicator("Y");
			else
				newIncident.setGroundsIssueIndicator("N");
			break;
		case R.id.groundsClosedCheckBox:
			if (checked)
				newIncident.setGroundsIssueClsdIndicator("Y");
			else
				newIncident.setGroundsIssueClsdIndicator("N");
			break;
		case R.id.mechanicalIssueCheckBox:
			if (checked)
				newIncident.setMechIssueIndicator("Y");
			else
				newIncident.setMechIssueIndicator("N");
			break;
		case R.id.mechanicalClosedCheckBox:
			if (checked)
				newIncident.setMechIssueClsdIndicator("Y");
			else
				newIncident.setMechIssueClsdIndicator("N");
			break;
		case R.id.otherIssueCheckBox:
			if (checked)
				newIncident.setOtherIssueIndicator("Y");
			else
				newIncident.setOtherIssueIndicator("N");
			break;
		case R.id.otherClosedCheckBox:
			if (checked)
				newIncident.setOtherIssueClsdIndicator("Y");
			else
				newIncident.setOtherIssueClsdIndicator("N");
			break;
		case R.id.plumbingIssueCheckBox:
			if (checked)
				newIncident.setPlumbIssueIndicator("Y");
			else
				newIncident.setPlumbIssueIndicator("N");
			break;
		case R.id.plumbingClosedCheckBox:
			if (checked)
				newIncident.setPlumbIssueClsdIndicator("Y");
			else
				newIncident.setPlumbIssueClsdIndicator("N");
			break;
		case R.id.roofsIssueCheckBox:
			if (checked)
				newIncident.setRoofsIssueIndicator("Y");
			else
				newIncident.setRoofsIssueIndicator("N");
			break;
		case R.id.roofsClosedCheckBox:
			if (checked)
				newIncident.setRoofsIssueClsdIndicator("Y");
			else
				newIncident.setRoofsIssueClsdIndicator("N");
			break;
		case R.id.safetyIssueCheckBox:
			if (checked)
				newIncident.setSafetyIssueIndicator("Y");
			else
				newIncident.setSafetyIssueIndicator("N");
			break;
		case R.id.safetyClosedCheckBox:
			if (checked)
				newIncident.setSafetyIssueClsdIndicator("Y");
			else
				newIncident.setSafetyIssueClsdIndicator("N");
			break;
		case R.id.structuralIssueCheckBox:
			if (checked)
				newIncident.setStructIssueIndicator("Y");
			else
				newIncident.setStructIssueIndicator("N");
			break;
		case R.id.structuralClosedCheckBox:
			if (checked)
				newIncident.setStructIssueClsdIndicator("Y");
			else
				newIncident.setStructIssueClsdIndicator("N");
			break;

		}// end switch
	}

	private void recordSpinnerSelection() {
		newIncident.setIncidentYear(Integer.valueOf(eventYearDropdown.getSelectedItem().toString()));
		newIncident.setEventName(eventNameDropdown.getSelectedItem().toString());

		propertyTypeDropdown = (Spinner) findViewById(R.id.propertyTypeDropdown);
		newIncident.setBuildingType(propertyTypeDropdown.getSelectedItem().toString());

		buildingStatusDropdown = (Spinner) findViewById(R.id.buildingStatusDropdown);
		newIncident.setBuildingStatus(buildingStatusDropdown.getSelectedItem().toString());

		creLeadDropdown = (Spinner) findViewById(R.id.creLeadDropdown);
		newIncident.setCreLead(creLeadDropdown.getSelectedItem().toString());

		reportOpenClosedSpinner = (Spinner) findViewById(R.id.reportOpenCloseDropdown);
		newIncident.setIncidentStatus(reportOpenClosedSpinner.getSelectedItem().toString());

	}

	private void readEditTextFields() {
		if (contactNumberEdit.getText().toString().equals("")) {
			reqFields = reqFields + " -Contact Number\n";
			reqCheck = false;
		} else
			newIncident.setContactPhone(contactNumberEdit.getText().toString().replaceAll("\\D+", ""));
		if (!capitalEdit.getText().toString().equals(""))
			newIncident.setEstCapCost(Integer.parseInt(capitalEdit.getText().toString()));
		if (!expenseEdit.getText().toString().equals(""))
			newIncident.setEstExpenseCost(Integer.parseInt(expenseEdit.getText().toString()));

		newIncident.setAssessNotes(assessmentEdit.getText().toString());
		newIncident.setStatusNotes(statusEdit.getText().toString());
		newIncident.setIncidentNotes(notesEdit.getText().toString());

		if (initialDateReportEdit.getText().toString().equals("")) {
			reqFields = reqFields + " -Inital Report Date Date\n";
			reqCheck = false;
		} else
			newIncident.setInitialRptDate(initialDateReportEdit.getText().toString());
		if (completionDateEdit.getText().toString().equals("")) {
			reqFields = reqFields + " -Completion Date\n";
			reqCheck = false;
		} else
			newIncident.setCompltnDate(completionDateEdit.getText().toString());
		newIncident.setWorkReqNumber(workRequestNumber.getText().toString());
	}

	public void startWebservice(View view) {

		imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);

		progressDialog.show();

		new AddIncidentAsyncTaskClass().execute();
	}

	private class AddIncidentAsyncTaskClass extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			submitNewAssessment();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			progressDialog.dismiss();
			if (!reqCheck) {
				DialogBox failWindow = new DialogBox(reqFields, false, getApplicationContext());
				failWindow.show(getSupportFragmentManager(), "RequiredFieldsNotFilled");
				reqFields = "The following fields are required:\n";
				reqCheck = true;
			} else {
				DialogBox successWindow = new DialogBox("Incident was added successfully!", true, getApplicationContext());
				successWindow.show(getSupportFragmentManager(), "SuccessFragment");
			}
		}
	}

	public void submitNewAssessment() {
		readEditTextFields();
		recordSpinnerSelection();
		try {
			if (reqCheck) {
				AddAssessmentWebservice.addIncident(sessionInfo.get(session.KEY_SESSION_TOKEN_ID), newIncident);
			}
		} catch (TokenInvalidException e) {
			e.printStackTrace();
		} catch (GeolocInvalidException e) {
			e.printStackTrace();
		}
	}
}